<?php
 /*
  * 用户登录
  */
namespace app\common\business;
use app\common\lib\Str;
use app\common\lib\Time;
use  app\common\model\mysql\User as UserObj;
use think\Exception;

class  User {
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserObj();
    }

    public function login($data){
//         $redisCode = cache(config('redis.code_pre').$data['phone_number']);
//         if(empty($redisCode) || ($redisCode != $data['code'])){
//             throw new \think\Exception('不存在该验证码',-10002);
//         }
         //生成token
         $user=$this->userObj->getUserByPhoneNumber($data['phone_number']);
         if(!$user){
              $username = "singwa粉丝-".$data['phone_number'];
              $userData = [
                  'username'=>$username,
                  'phone_number'=>$data['phone_number'],
                  'type'=>$data['type'],
                  'status'=>1
              ];
              try{
                  $this->userObj->save($userData);
                  $userId = $this->userObj->id;
              }catch (\Exception $e){
                  throw new Exception('数据库内部异常！！！');
              }
         } else{
             //更新
             $username = $user->username;
             $userId = $user->id;
         }
         $token = Str::getLoginToken($data['phone_number']);
         $this->userObj->updateUserToken($userId,$token);
         //存redis 里面
         $redisLoginData = [
             'id'=>$userId,
             'username'=>$username,
             'token'=>$token
         ];
         $loginTime = Time::getLoginTokenExpriseTime($data['type']);
         $res = cache(config('redis.token_pre').$token,$redisLoginData,$loginTime);
         return $res ? ['token'=>$token,'username'=>$username,'token_time'=>$loginTime] : false;
    }

    /*
     * 获取用户的信息
     */
    public function getNormalUserData($id){
        $user = $this->userObj->getUserId($id);
        if(!$user || ($user['status'] != config('status.mysql.table_normal'))){
            return [];
        }
        return $user->toArray();
    }
}